package com.superdry.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.http.AbHttpUtil;
import com.ab.http.AbRequestParams;
import com.ab.http.AbStringHttpResponseListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.drysurper.R;
import com.superdry.alipay.AliPayUtils;
import com.superdry.alipay.PayResult;
import com.superdry.json.Address;
import com.superdry.json.Coupon;
import com.superdry.json.OrderListItemBean;
import com.superdry.json.Userinfo;
import com.superdry.main.MainActivity;
import com.superdry.utils.GlobalConst;
import com.superdry.utils.SPHelper;
import com.superdry.utils.StringUtils;
import com.superdry.utils.ToastHelper;

public class PayOrderActivity extends Activity implements OnClickListener {

	private TextView pay_status;
	private TextView order_total_money;
	private TextView home_service_cost;
	private TextView coupon;
	private TextView integral;
	private TextView balance;
	private TextView post_address;
	private TextView post_cost;
	private TextView total_money;

	private TextView ali_pay;
	private TextView weixin_pay;
	private TextView count_pay;

	private RelativeLayout post;
	private LinearLayout pay_order_goback;
	private RelativeLayout coupon_rl;

	private OrderListItemBean order;
	private AbHttpUtil mAbHttpUtil = null;
	private ProgressDialog progressDialog;
	private Coupon coupon_choosed = null;

	private static final int ALI_PAY_FLAG = 1;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ALI_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);
				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					zhifu_success();
					Toast.makeText(PayOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(PayOrderActivity.this, MainActivity.class);
					intent.putExtra("cmd", GlobalConst.SHOW_ORDER_FRAGMENT);
					startActivity(intent);
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(PayOrderActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(PayOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_pay_order);
		initViews();
		initDatas();
	}

	/**
	 * 初始化各种view
	 */
	private void initViews() {
		// 获取Http工具类
		mAbHttpUtil = AbHttpUtil.getInstance(this);
		mAbHttpUtil.setTimeout(10000);

		pay_status = (TextView) findViewById(R.id.pay_status);
		order_total_money = (TextView) findViewById(R.id.order_total_money);
		home_service_cost = (TextView) findViewById(R.id.home_service_cost);
		coupon = (TextView) findViewById(R.id.coupon);
		integral = (TextView) findViewById(R.id.integral);
		balance = (TextView) findViewById(R.id.balance);
		post_address = (TextView) findViewById(R.id.post_address);
		post_cost = (TextView) findViewById(R.id.post_cost);
		total_money = (TextView) findViewById(R.id.total_money);

		count_pay = (TextView) findViewById(R.id.count_pay);
		weixin_pay = (TextView) findViewById(R.id.weixin_pay);
		ali_pay = (TextView) findViewById(R.id.ali_pay);

		post = (RelativeLayout) findViewById(R.id.post);
		coupon_rl = (RelativeLayout) findViewById(R.id.coupon_rl);
		pay_order_goback = (LinearLayout) findViewById(R.id.pay_order_goback);

		ali_pay.setOnClickListener(this);
		weixin_pay.setOnClickListener(this);
		count_pay.setOnClickListener(this);
		coupon_rl.setOnClickListener(this);
		post.setOnClickListener(this);
		pay_order_goback.setOnClickListener(this);
	}

	/**
	 * 初始化各种数据
	 */
	private void initDatas() {

		order = (OrderListItemBean) getIntent().getSerializableExtra("order");// 没有优惠券字段
		// 订单状态
		if (order.getOrderStatus() == 0) {
			pay_status.setText("未付款");
		}
		double money = Double.parseDouble((order.getSurplusMoney()));
		if (money > 58) {
			home_service_cost.setText(0.00 + "");
		} else {
			home_service_cost.setText(6.00 + "");
		}

		order_total_money.setText(order.getSurplusMoney() + "");
		post_address.setText("地址： " + order.getAddressName());
		integral.setText(SPHelper.getUserInfo(this).getIntegral() + "");
		refreshTotalMoney();
	}

	/**
	 * 刷新总金额
	 */
	private void refreshTotalMoney() {

		double money = Double.parseDouble(order_total_money.getText().toString());
		double service_cost = Double.parseDouble(home_service_cost.getText().toString());
		double coupon_d = Double.parseDouble(coupon.getText().toString());
		double post_cost_d = Double.parseDouble(post_cost.getText().toString());
		double total_ = money + service_cost + coupon_d + post_cost_d;
		total_money.setText(total_ + "");
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.post:
			// 改变快递地址
			Intent intent = new Intent(PayOrderActivity.this, Add_AddressActivity.class);
			intent.putExtra("cmd", "change_address");
			startActivityForResult(intent, 0);
			break;
		case R.id.pay_order_goback:
			// 返回
			finish();
			break;
		case R.id.coupon_rl:
			// 跳转到 选择优惠券 界面
			Intent i = new Intent(PayOrderActivity.this, CouponActivity.class);
			i.putExtra("money", order.getSurplusMoney());
			startActivityForResult(i, 1);
			break;
		case R.id.ali_pay:
			// 支付宝支付
			ali_pay();
			break;
		case R.id.weixin_pay:
			// 微信支付
			break;
		case R.id.count_pay:
			// 余额支付
			balance_pay();
			break;
		default:
			break;
		}
	}

	/**
	 * 余额支付
	 */
	private void balance_pay() {

		String tv = total_money.getText().toString();
		Userinfo info = SPHelper.getUserInfo(PayOrderActivity.this);
		if (StringUtils.isEmpty(tv) || info == null) {
			ToastHelper.show(PayOrderActivity.this, "参数有误");
			return;
		}
		double money = Double.parseDouble(tv);
		if (info.getAccount() < money) {
			// 余额不足
			ToastHelper.show(PayOrderActivity.this, "余额不足");
			return;
		}
		// 异步支付
		AbRequestParams params = new AbRequestParams();
		params.put("orderGoodsId", order.getOrderGoodsId());
		params.put("orderID", order.getOrderID());
		params.put("userID", info.getUserID() + "");
		String s =  total_money.getText().toString();
		params.put("surplusMoney", total_money.getText().toString());
		params.put("orderGoodsId", order.getOrderGoodsId() + "");
		params.put("allMoney", order.getSurplusMoney() + "");
		// 优惠券id
		if (coupon_choosed != null) {
			params.put("couponID", coupon_choosed.getCouponID() + "");
		}
		params.put("account", info.getAccount() + "");
		// 剩余积分
		params.put("integral", info.getIntegral() + "");

		mAbHttpUtil.post(GlobalConst.GET_BALANCE_PAY, params, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
				progressDialog = progressDialog.show(PayOrderActivity.this, "支付中...", "请稍后 ...");
			}

			@Override
			public void onFinish() {
			}

			@Override
			public void onFailure(int statusCode, String content, Throwable error) {
				progressDialog.dismiss();
				ToastHelper.show(PayOrderActivity.this, "支付失败");
			}

			@Override
			public void onSuccess(int statusCode, String content) {

				JSONObject object = JSONObject.parseObject(content);
				int i = object.getInteger("i");
				if (i > 0) {
					ToastHelper.show(PayOrderActivity.this, "支付成功");
					Intent intent = new Intent(PayOrderActivity.this, MainActivity.class);
					intent.putExtra("cmd", GlobalConst.SHOW_ORDER_FRAGMENT);
					startActivity(intent);
				} else {
					ToastHelper.show(PayOrderActivity.this, "支付失败");
				}
			}
		});

	}

	/**
	 * 支付宝支付
	 */
	private void ali_pay() {
		// 订单
		String orderInfo = AliPayUtils.getOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");
		// 对订单做RSA 签名
		String sign = AliPayUtils.sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + AliPayUtils.getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(PayOrderActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = ALI_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};
		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * 通知服务器 支付成功
	 */
	public void zhifu_success() {

		AbRequestParams params = new AbRequestParams();
		params.put("result", "1");
		params.put("orderId", order.getOrderID());
		if (coupon_choosed != null) {
			params.put("couponID", coupon_choosed.getCouponID());
		} else {
			params.put("couponID", "");
		}

		mAbHttpUtil.post(GlobalConst.ZHIFU_SUCCESS, params, new AbStringHttpResponseListener() {

			@Override
			public void onStart() {
			}

			@Override
			public void onFinish() {
			}

			@Override
			public void onFailure(int statusCode, String content, Throwable error) {
				progressDialog.dismiss();
				ToastHelper.show(PayOrderActivity.this, "支付失败");
			}

			@Override
			public void onSuccess(int statusCode, String content) {

				JSONObject object = JSONObject.parseObject(content);
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 在选择优惠券 或者 快递之后要更新 消费的总金额
		if (data == null)
			return;
		if (requestCode == 1) {
			// 优惠券
			coupon_choosed = (Coupon) data.getSerializableExtra("coupon");
			if (coupon_choosed != null) {
				coupon.setText(coupon_choosed.getCouponPrice() + "");
			} else {
				coupon.setText(0.00 + "");
			}

		} else if (requestCode == 0) {
			// 改变快递地址
			Address address = (Address) data.getSerializableExtra("address");
			post_address.setText(" 地址：" + address.getAddressName());
		}
	}

	/**
	 * 得到用户优惠券
	 */
	/*
	 * private void doGetCoupon() {
	 * 
	 * AbRequestParams params = new AbRequestParams(); params.put("userID",
	 * SPHelper.getUserInfo(PayOrderActivity.this).getUserID() + "");
	 * params.put("allMoney", order.getSurplusMoney() + "");
	 * mAbHttpUtil.post(GlobalConst.GET_CHOOSE_COUPONS, params, new
	 * AbStringHttpResponseListener() {
	 * 
	 * @Override public void onStart() {
	 * 
	 * }
	 * 
	 * @Override public void onFinish() {
	 * 
	 * }
	 * 
	 * @Override public void onFailure(int statusCode, String content, Throwable
	 * error) {
	 * 
	 * }
	 * 
	 * @Override public void onSuccess(int statusCode, String content) {
	 * List<Coupon> coupons = JSON.parseArray(content, Coupon.class); //
	 * 跳转到优惠券页面 Intent intent = new Intent(PayOrderActivity.this,
	 * CouponActivity.class); startActivity(intent);
	 * 
	 * } }); }
	 */

}
